package net.oschina.simpleplus.tcp;

import java.net.InetSocketAddress;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import net.oschina.simpleplus.core.BaseServer;
import net.oschina.simpleplus.core.SnowFlake;

public class TcpServer extends BaseServer {
	
	private SnowFlake snowFlake;
	
	public TcpServer(SnowFlake snowFlake) {
		super();
		this.snowFlake = snowFlake;
	}

	@Override
	public void init() {
		super.init();
		b.group(bossGroup, workGroup)
        .channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_KEEPALIVE, true)
        .option(ChannelOption.TCP_NODELAY, true)
        .option(ChannelOption.SO_BACKLOG, 1024)
        .localAddress(new InetSocketAddress(port))
        .childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(defLoopGroup,
                        new PacketDecoder(12),  // 自定义解码器
                        new PacketEncoder(),    // 自定义编码器
                        new PacketHandler(snowFlake) // 自定义处理器
                );
            }
        });
	}
	
	@Override
    public void start() {
        try {
            cf = b.bind().sync();
            InetSocketAddress addr = (InetSocketAddress) cf.channel().localAddress();
            logger.info("start success, port is:{}", addr.getPort());
        } catch (InterruptedException e) {
            logger.error("start fail,", e);
        }
    }

}
